<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Friend
 *  
 * @author tuancasi
 */
class FriendRequest extends CActiveRecord {

    public $senderName = '';

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{friend_requests}}';
    }

    public function rules() {
	return array(
	    array('friend_request_id, user_send, user_receive, time_created, senderName', 'safe')
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_send'),
	    'userSender' => array(self::BELONGS_TO, 'User', 'user_receive')
	);
    }

    /**
     * invite friend
     */
    public static function insertRequest($userSend, $userReceive) {
	$time = date('Y-m-d h:i:s', time());
	Yii::app()->db->createCommand("INSERT INTO {{friend_requests}}(`user_send`, `user_receive`, `time_created`) VALUES(" . $userSend . ", " . $userReceive . ", '" . $time . "')")->execute();
	$aIdFriendRequested = Yii::app()->cache->get('aIdFriendRequested' . $userSend);
	if ($aIdFriendRequested !== false) {
	    Yii::app()->cache->delete('aIdFriendRequested' . $userSend);
	}
    }

    /**
     * delete request
     */
    public static function deleteRequest($userSend, $userReceive) {
	Yii::app()->db->createCommand("DELETE FROM {{friend_requests}} WHERE user_send=" . $userSend . " and user_receive=" . $userReceive)->execute();
	$aIdFriendRequesteds = Yii::app()->cache->get('aIdFriendRequested' . $userSend);
	if ($aIdFriendRequesteds !== false) {
	    Yii::app()->cache->delete('aIdFriendRequested' . $userSend);
	}
    }

    /**
     * 
     * @return \CActiveDataProvider
     */
    public function search($id, $type) {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;

	$criteria->alias = 't';
	if ($type == 'incoming') {
	    $criteria->addCondition('t.user_receive = ' . $id);
	    $criteria->with = array("user");
	} else {
	    $criteria->addCondition('t.user_send = ' . $id);
	    $criteria->with = array("userSender");
	}
	$criteria->compare('user.username', $this->senderName, true);
	//order	

	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	    'pagination' => array(
		'pageSize' => param('pageSize')
	    ),
	    'sort' => array(
		'defaultOrder' => array(
		    'time_created' => CSort::SORT_DESC
		)
	    )
	));
    }

    /**
     * get num of friend have invited you recently
     * @param type $userId
     * @return type
     */
    public static function getFriendRequest($userId) {
	$data = Yii::app()->db->createCommand(
			"SELECT COUNT(friend_request_id) as num_friend_requested 
			FROM {{friend_requests}}   
			WHERE is_read =  " . NOT_READ . " and user_receive = " . $userId)->queryRow();
	return $data['num_friend_requested'];
    }

    /**
     * get friend have invited you recently
     * @param type $userId
     * @return type
     */
    public static function getNumPendingRequest($userId) {
	$data = Yii::app()->db->createCommand(
			"SELECT COUNT(friend_request_id) as num_pending_requested 
			FROM {{friend_requests}}   
			WHERE is_read =  " . NOT_READ . " and user_send = " . $userId)->queryRow();
	return $data['num_pending_requested'];
    }

    /**
     * set user have checked inviting from others
     */
    public static function updateChecked($userId) {
	Yii::app()->db->createCommand("UPDATE {{friend_requests}} SET is_read = " . READED . " WHERE is_read =  " . NOT_READ . " and user_receive = " . $userId)->execute();
    }

    /**
     * set user have checked pending request
     */
    public static function updateCheckedPending($userId) {
	Yii::app()->db->createCommand("UPDATE {{friend_requests}} SET is_read = " . READED . " WHERE is_read =  " . NOT_READ . " and user_send = " . $userId)->execute();
    }

    public static function getIdsSendTo($idSender) {

	$aIdFriendRequested = Yii::app()->cache->get('aIdFriendRequested' . $idSender);
	if ($aIdFriendRequested === false) {
	    $aIdFriendRequested = array();
	    $aFriendRequested = Yii::app()->db->createCommand('SELECT * FROM {{friend_requests}} WHERE user_send=' . $idSender)->queryAll();
	    foreach ($aFriendRequested as $friend) {
		$aIdFriendRequested[] = $friend['user_receive'];
	    }
	    Yii::app()->cache->set('aIdFriendRequested' . $idSender, $aIdFriendRequested);
	}
	return $aIdFriendRequested;
    }

}

